# -*- coding: utf-8 -*-
# ☯ Author: ChinaPython
# ☯ Email : chinapython@yeah.net
# ☯ Date  : 2021/10/12 23:38
import os
from flask import Flask
from flask import jsonify
from flask import request
from pytube import YouTube

app = Flask(__name__)


@app.route('/', methods=['GET'])
def index():
    # 获取参数
    u, v, m = request.args.get('user'), request.args.get('vid'), request.args.get('mode')
    # 判断相关参数
    if u != "robin" or len(str(v)) != 11 or m not in ["dl", "del"]:
        return jsonify({"code": "403", "url": "", "msg": "参数错误"})
    # 下载模式
    if m == "dl":
        try:
            # 下载视频
            info = YouTube(url=f'https://www.youtube.com/watch?v={v}')
            stream = info.streams.get_by_itag(140)
            stream.download(filename=f"./static/{v}.m4a")
            # 判断视频下载 不存在
            if os.path.exists(f"./static/{v}.m4a") is False:
                return jsonify({"code": "501", "url": "", "msg": "下载失败"})
            # 大小对比
            if stream.filesize != os.path.getsize(f"./static/{v}.m4a"):
                # 文件有差异  删除
                os.remove(f"./static/{v}.m4a")
                return jsonify({"code": "502", "url": "", "msg": "文件异常"})
            # 返回数据
            return jsonify({"code": "200", "url": '{}/static/{}.m4a'.format(request.url_root, v), "msg": "数据正常"})
        except Exception as e:
            return jsonify({"code": "503", "url": "", "msg": "{},{}".format("框架错误:", str(e))})
    # 删除模式
    # 判断文件在不在
    if os.path.exists(f"./static/{v}.m4a") is False:
        return jsonify({"code": "504", "url": "", "msg": "删除失败:未发现文件"})
    # 删除文件
    os.remove(f"./static/{v}.m4a")
    return jsonify({"code": "200", "url": "", "msg": "删除成功"})


if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=8080,
        debug=False
    )
